define(function (require, exports, module) {
    require('/includes/libraries/javascript/placeholder.js');
    require('/includes/libraries/javascript/validation.js');
    require('/includes/libraries/javascript/suggest');
    require('/includes/libraries/javascript/dialog');
    // input
    var form = $("#register-form");
    
    //密码
    var form_oldpwd = $("#form-olpwd");
    var form_pwd = $("#form-pwd");
    var form_equalTopwd = $("#form-equalTopwd");

   
    var auth_code = $("#authCode");
   
    var icons = {
        def: '<i class="i-def"></i>',
        error: '<i class="i-error"></i>',
        weak: '<i class="i-pwd-weak"></i>',
        medium: '<i class="i-pwd-medium"></i>',
        strong: '<i class="i-pwd-strong"></i>'
    };
   
    suggestsList = {};

    function init() {
        initPlaceholer();
      
        checkPwd();
        
        validate();
        
        bindEvent();
    }
    function getStringLength(str){
        if(!str){
            return;
        }
        var bytesCount=0;
        for (var i = 0; i < str.length; i++)
        {
            var c = str.charAt(i);
            if (/^[\u0000-\u00ff]$/.test(c))
            {
                bytesCount += 1;
            }
            else
            {
                bytesCount += 2;
            }
        }
        return bytesCount;
    }
    function resetStringLength(length,_id){
        _id='#'+_id;
        while(getStringLength($(_id).val())>length){
            $(_id).val($(_id).val().substring(0,$(_id).val().length-1))
        }
    }
    function bindEvent(){
        $('input').bind('input',function(){
            var _id=$(this).attr('id');
            switch(_id){
                //case 'form-account':
                //    resetStringLength(20,_id);
                //    break;
                case 'form-equalTopwd':
                case 'form-pwd':
                    resetStringLength(20,_id);
                    break;
                case 'form-email':
                    resetStringLength(50,_id);
                    break;
                case 'form-phone':
                    resetStringLength(11,_id);
                    break;
                case 'authCode':
                case'phoneCode':
                    resetStringLength(6,_id);
                    break;
            }
        })
    }
    //表单验证
    var validator;

    function validate() {
        addrules();
        validator = form.validate({
            //忽略
            ignore: '.ignore',
            submitHandler: function (form) {
                //提交表单
                formSubmit(form);
                //阻止表单提交
                return false;
            },
            onkeyup: false,
            rules: {
            	oldpwd: {
                    required: true
                },
                //密码
                pwd: {
                    required: true,
                    rangelength: [6, 20],
                    strength: true,
                    same: '#form-account'
                },
                pwdRepeat: {
                    required: true,
                    equalTo: '#form-pwd'
                },            
                authcode: {
                    required: true
                }
            },
            messages: {
            	oldpwd: {
                    required: icons.error + '请输入原始密码',
                },
                pwd: {
                    required: icons.error + '请输入密码',
                    rangelength: icons.error +
                    '长度只能在{0}-{1}个字符之间'
                },
                pwdRepeat: {
                    required: icons.error + '请再次输入密码',
                    equalTo: icons.error + '两次密码输入不一致'
                },
                authcode: {
                    required: icons.error + '请输入图片验证码'
                }
            }
        });
    }
    //提交表单
    function formSubmit(form) {
        $btnRegister = $("#form-register");
        var param = $(form).serialize();
        var ajaxurl = '/index.php?';
        $.ajax({
            type: 'post',
            url: ajaxurl + location.search.substring(1),
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: param,
            cache:false,
            beforeSend: function () {
                $btnRegister.text('正在修改..');
            },
            error: function () {
                showDialog('网络繁忙，请稍后再试');
            },
            success: function (response) {
                if (response) {
                    var obj = eval(response);
                    
                    if (obj.success) {
                    	showDialog("修改密码成功");
                    	setTimeout(function(){

                            successRedirectURL(obj.success);
                    	},2000);
                    }
                    
                    if (obj.info) {
                    	change_captcha($('#captcha'));
                        showDialog(obj.info);
                    }
                    
                }
                $btnRegister.text('确认修改');
            }
        });
    }
    
    //验证规则
    function addrules() {
        //用户名
        $.validator.addMethod('user', function (value, element) {
            return this.optional(element) ||
                /^[A-Za-z0-9_\-\u4e00-\u9fa5]+$/.test(value);
        }, icons.error + '格式错误，仅支持汉字、字母、数字、“-”“_”的组合');
        $.validator.addMethod('fullNumber', function (value, element) {
            return this.optional(element) || !/^[0-9]+$/.test(
                    value);
        }, icons.error + '用户名不能是纯数字，请重新输入！');
        
        $.validator.addMethod('phone', function (value, element) {
            //var country_id = selectCountry.attr("country_id");
            var reg = {
                //海外手机注册
                //"86": "^(13|15|18|14|17)[0-9]{9}$", //中国
                "0086": "^(13|15|18|14|17)[0-9]{9}$", //中国
            }
            return this.optional(element) || new RegExp(reg[
                    "0086"]).test(value);
        }, icons.error + '格式有误');
        
        //密码
        $.validator.addMethod('strength', function (value, element) {
            return this.optional(element) || pwdStrengthRule($(
                    element), value);
        }, icons.weak + '有被盗风险,建议使用字母、数字和符号两种及以上组合');
        $.validator.addMethod('same', function (value, element, param) {
            var target = $(param);
            return value !== target.val();
        }, icons.error + '密码与用户名相似，有被盗风险，请更换密码');
    }
    // checkpwd
    var weakPwds = ["123456", "123456789", "111111", "5201314",
        "12345678", "123123", "password", "1314520", "123321",
        "7758521", "1234567", "5211314", "666666", "520520",
        "woaini", "520131", "11111111", "888888", "hotmail.com",
        "112233", "123654", "654321", "1234567890", "a123456",
        "88888888", "163.com", "000000", "yahoo.com.cn", "sohu.com",
        "yahoo.cn", "111222tianya", "163.COM", "tom.com", "139.com",
        "wangyut2", "pp.com", "yahoo.com", "147258369", "123123123",
        "147258", "987654321", "100200", "zxcvbnm", "123456a",
        "521521", "7758258", "111222", "110110", "1314521",
        "11111111", "12345678", "a321654", "111111", "123123",
        "5201314", "00000000", "q123456", "123123123", "aaaaaa",
        "a123456789", "qq123456", "11112222", "woaini1314",
        "a123123", "a111111", "123321", "a5201314", "z123456",
        "liuchang", "a000000", "1314520", "asd123", "88888888",
        "1234567890", "7758521", "1234567", "woaini520",
        "147258369", "123456789a", "woaini123", "q1q1q1q1",
        "a12345678", "qwe123", "123456q", "121212", "asdasd",
        "999999", "1111111", "123698745", "137900", "159357",
        "iloveyou", "222222", "31415926", "123456", "111111",
        "123456789", "123123", "9958123", "woaini521", "5201314",
        "18n28n24a5", "abc123", "password", "123qwe", "123456789",
        "12345678", "11111111", "dearbook", "00000000", "123123123",
        "1234567890", "88888888", "111111111", "147258369",
        "987654321", "aaaaaaaa", "1111111111", "66666666",
        "a123456789", "11223344", "1qaz2wsx", "xiazhili",
        "789456123", "password", "87654321", "qqqqqqqq",
        "000000000", "qwertyuiop", "qq123456", "iloveyou",
        "31415926", "12344321", "0000000000", "asdfghjkl",
        "1q2w3e4r", "123456abc", "0123456789", "123654789",
        "12121212", "qazwsxedc", "abcd1234", "12341234",
        "110110110", "asdasdasd", "123456", "22222222", "123321123",
        "abc123456", "a12345678", "123456123", "a1234567",
        "1234qwer", "qwertyui", "123456789a", "qq.com", "369369",
        "163.com", "ohwe1zvq", "xiekai1121", "19860210", "1984130",
        "81251310", "502058", "162534", "690929", "601445",
        "1814325", "as1230", "zz123456", "280213676", "198773",
        "4861111", "328658", "19890608", "198428", "880126",
        "6516415", "111213", "195561", "780525", "6586123",
        "caonima99", "168816", "123654987", "qq776491",
        "hahabaobao", "198541", "540707", "leqing123", "5403693",
        "123456", "123456789", "111111", "5201314", "123123",
        "12345678", "1314520", "123321", "7758521", "1234567",
        "5211314", "520520", "woaini", "520131", "666666",
        "RAND#a#8", "hotmail.com", "112233", "123654", "888888",
        "654321", "1234567890", "a123456"
    ];
    var pwdStrength = {
        1: {
            reg: /^.*([\W_])+.*$/i,
            msg: icons.weak + '有被盗风险,建议使用字母、数字和符号两种及以上组合'
        },
        2: {
            reg: /^.*([a-zA-Z])+.*$/i,
            msg: icons.medium + '安全强度适中，可以使用三种以上的组合来提高安全强度'
        },
        3: {
            reg: /^.*([0-9])+.*$/i,
            msg: icons.strong + '你的密码很安全'
        }
    };

    function pwdStrengthRule(element, value) {
        var level = 0;
        var typeCount=0;
        var flag = true;
        var valueLength=getStringLength(value);
        if (valueLength < 6) {
            element.parent().removeClass('form-item-valid').removeClass(
                'form-item-error');
            element.parent().next().find('span').removeClass('error').html(
                $(element).attr('default'));
            return;
        }

        for (key in pwdStrength) {
            if (pwdStrength[key].reg.test(value)) {
                typeCount++;
            }
        }
        if(typeCount==1){
            if(valueLength>10){
                level=2;
            }else{
                level=1;
            }
        }else if(typeCount==2){
            if(valueLength<11&&valueLength>5){
                level=2;
            }
            if(valueLength>10){
                level=3;
            }
        }else if(typeCount==3){
            if(valueLength>6){
                level=3;
            }
        }

        if ($.inArray(value, weakPwds) !== -1) {
            flag = false;
            level=1;
        }
        if (flag && level > 0) {
            element.parent().removeClass('form-item-error').addClass(
                'form-item-valid');
        } else {
            element.parent().addClass('form-item-error').removeClass(
                'form-item-valid');
        }
        if (pwdStrength[level] !== undefined) {
            pwdStrength[level]>3?pwdStrength[level]=3:pwdStrength[level];
            element.parent().next().html('<span>' + pwdStrength[level].msg +
            '</span>')
        }
        return flag;
    }

    function filterKey(e) {
        var excludedKeys = [13, 9, 16, 17, 18, 20, 35, 36, 37, 38,
            39,
            40, 45, 144, 225
        ];
        return $.inArray(e.keyCode, excludedKeys) !== -1;
    }

    function checkPwd() {
        form_pwd.on('keyup', function (e) {
            var value = $(this).val();
            pwdStrengthRule(form_pwd, value);
        })
    }

    function hideError(input, msg) {
        var item = input.parent();
        var msg = msg || input.attr('default');
        item.removeClass('form-item-error form-item-valid');
        item.next().find('span').removeClass('error').html(msg).show();
        item.next().removeClass('phone-bind-tip');
        item.removeClass('phone-binded');
    }
    /**输入过程中处理标签的状态**/
    function onKeyupHandler(input, msg) {
        var item = input.parent();
        if (!item.hasClass('form-item-error')) {
            item.addClass('form-item-error')
        }
        item.removeClass('form-item-valid');
        item.next().find('span').addClass('error').html(msg).show();
    }

    function initPlaceholer() {
        $('input[placeholder]').placeholder({
            isValue: true,
            topDiff: 1
        });
    }

    function showDialog(content) {
        $('body').dialog({
            title: '提示',
            fixed: true,
            width: 380,
            //height: 150,
            maskClose: true,
            type: 'html',
            source: '<div class="registerDialog">\
                        <div class="ico"></div>\
                        <div class="con">\
                        ' +
            content +
            '\
                    </div></div>'
        })
    }
    exports.init = init;
})
function successRedirectURL(url){
    var isIE = !-[1,];
    if(isIE){
        var link = document.createElement("a");
        link.href = url;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.target = "_top";
        link.click();
    }else{
        window.top.location = url;
    }
}

function change_captcha(jqObj){
    jqObj.attr('src', 'index.php?app=captcha&' + Math.round(Math.random()*10000));
}